package model.webService.translation;

import java.util.HashMap;

import model.OnScreen;
import model.snippet.Snippet;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Used for translating JSON to snippets.
 */
public class JSONBehaviour extends ServiceBehaviour {

	@SuppressWarnings("unused")
	private static final String TAG = JSONBehaviour.class.getSimpleName();

	@Override
	public void translateResponse(String response) throws JSONException
	{

		HashMap<String, Snippet> snippets = OnScreen.getInstance().getSnippets();
		String id;			
					
			
		JSONArray jsonArray = new JSONArray(response);
		for(int i = 0; i < jsonArray.length(); i ++)
		{
			JSONObject jsonSnippet;
			
			jsonSnippet = jsonArray.getJSONObject(i);
			
			id = jsonSnippet.getString("ID");
			
			
			//If snippet already exists, update instead of create
			if(snippets.containsKey(id))
			{	
				//Value is the only variable data
				snippets.get(id).setStatus(jsonSnippet.getBoolean("Value"));
				continue;
			}
			
			JSONObject jsonDimension = jsonSnippet.getJSONObject("Size");
			JSONObject jsonWorldCoord = jsonSnippet.getJSONObject("Coordinate");				
			
			Snippet snippet = createSnippet(
					id, 
					jsonWorldCoord.getInt("X"), jsonWorldCoord.getInt("Y"), jsonWorldCoord.getInt("Z"), 
					jsonDimension.getInt("Width"), jsonDimension.getInt("Height"), 
					jsonSnippet.getBoolean("Value"), jsonSnippet.getInt("Display")
				);
			
			snippets.put(id, snippet);
		}
	}
	
	/**
	 * Checks whether given string is valid JSON
	 * @param test The string to check.
	 * @deprecated This method is no longer used.
	 * @return True if given string is in the right format
	 */
	public boolean isJSONValid(String test)
	{
	    try {
	        new JSONObject(test);
	        return true;
	    } catch(JSONException ex) { 
	        return false;
	    }
	}
}
